package com.abing.shiro.realm;

import com.abing.shiro.dao.IPermissionDAO;
import com.abing.shiro.dao.IRoleDAO;
import com.abing.shiro.dao.IUserDAO;
import com.abing.shiro.domain.User;
import lombok.Setter;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class UserRealm extends AuthorizingRealm {

    @Setter
    private IUserDAO userDAO;
    @Setter
    private IRoleDAO roleDAO;
    @Setter
    private IPermissionDAO permissionDAO;
    @Override
    public String getName() {
        return "UserRealm";
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        User user= (User) principalCollection.getPrimaryPrincipal();
        List<String> permissions = new ArrayList<String>();
        List<String> roles = new ArrayList<>();
        if ("admin".equals(user.getUsername())){
            //拥有所有的权限
            permissions.add("*:*");
            //查询所有的角色，并且拥有
            roles=roleDAO.getAllRoleSn();
        }else{
            //查询拥有所有的权限
            permissions=permissionDAO.getPermissionResourceByUserId(user.getId());
            //查询所有的角色，并且拥有
            roles=roleDAO.getRoleSnByUserId(user.getId());
        }
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addStringPermissions(permissions);
        info.addRoles(roles);
        return info;
    }
    //认证

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //從token中獲取登錄的用戶名，鏟鱘數據庫返回用戶信息
        String userName= (String) authenticationToken.getPrincipal();
        User user=userDAO.getUserByUsername(userName);
        if (user==null){
            return null;
        }
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user,user.getPassword(),ByteSource.Util.bytes(user.getUsername()),getName());
        return info;
    }

    @Override
    protected void clearCache(PrincipalCollection principals) {
        //获取当前用户登陆的数据，然后清除
//        PrincipalCollection principalCollection=SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principals);
    }
}
